<template>
  <div class="login contain">
    <h1 style="text-align: center; margin: 20px auto; font-size: 35px">
      {{ pageType ? "注册" : "登录" }}
    </h1>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm loginForm"
    >
      <el-form-item label="头像" v-if="pageType">
        <el-upload
          class="avatar-uploader"
          name="avatar"
          :auto-upload="false"
          action="http://127.0.0.1:3009/api/v1/auth/reg"
          :data="ruleForm"
          :show-file-list="false"
          ref="avatarUpload"
          :on-success="handleAvatarSuccess"
          :on-change="onChange"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName" v-if="pageType">
        <el-input v-model="ruleForm.nickName"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone" v-if="pageType">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="passWord">
        <el-input
          type="password"
          show-password
          v-model="ruleForm.passWord"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="repassWord" v-if="pageType">
        <el-input
          type="password"
          show-password
          v-model="ruleForm.repassWord"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱" v-if="pageType">
        <el-input v-model="ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender" v-if="pageType">
        <el-radio-group v-model="ruleForm.gender">
          <el-radio label="1">男</el-radio>
          <el-radio label="0">女</el-radio>
          <el-radio label="2">保密</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">{{
          pageType ? "注册并登录" : "登录"
        }}</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="primary" @click="goReg" v-if="!pageType"
          >没有账号？去注册</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Login",
  computed: {
    pageType() {
      // console.log(this.$route.meta.type);
      return this.$route.meta.type == "reg";
    },
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.passWord) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      imageUrl: "http://127.0.0.1:3009/public/avatar/avatar.jpg",
      ruleForm: {
        userName: "",
        passWord: "",
        repassWord: "",
        gender: "1",
        email: "",
        phone: "",
        nickName: "",
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]{1,10}$/, //用户名验证
            message: "请输入1-10个字母、数字、'_'组合",
            trigger: ["change", "blur"],
          },
        ],
        nickName: [
          {
            min: 1,
            max: 18,
            message: "长度在 1 到 18 个字符",
            trigger: "blur",
          },
          {
            pattern: /^([\u4e00-\u9fa5]|\d|\w){1,12}$/, //昵称验证
            message: "请输入1-12个汉字、字母、数字和“_”组合",
            trigger: ["change", "blur"],
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^\d{11}$/, //手机号验证
            message: "手机号格式错误",
            trigger: ["blur"],
          },
        ],
        passWord: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur",
          },
          {
            pattern: /^\w*$/, //密码验证
            message: "请输入字母、数字或者_",
            trigger: ["change", "blur"],
          },
          { validator: validatePass, trigger: "blur" },
        ],
        repassWord: [
          {
            required: true,
            message: "请确定密码",
            trigger: "blur",
          },
          { validator: validatePass2, trigger: "blur" },
        ],
        email: [
          { required: false, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur"],
          },
        ],
      },
    };
  },
  methods: {
    goReg() {
      this.$router.push("/reg");
    },
    onChange(file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res);
      let mydate = new Date();
      mydate.setDate(mydate.getDate + 15);
      if (res.code == 1) {
        document.cookie = `token=${res.token};expires=${mydate}`;
        sessionStorage.setItem("token", res.token);
        this.$store.commit("initUser", JSON.stringify(res.data));
        this.$message({
          message: "注册成功，跳转首页",
          type: "success",
        });
        this.$router.push("/home");
      } else {
        this.$msgbox({
          title: "注册失败",
          message: res.msg,
          type: "warning",
        });
      }
    },
    submitForm(formName) {
      let flag = null;
      this.$refs[formName]?.validate((valid, obj) => {
        flag = valid;
      });
      if (flag !== false) {
        let type = this.$route.meta.type;
        if (type == "reg") {
          this.$refs.avatarUpload.submit();
        } else if (type == "login") {
          // console.log(login);
          this.axios
            .post("/api/v1/auth/login", {
              userName: this.ruleForm.userName,
              passWord: this.ruleForm.passWord,
            })
            .then((res) => {
              if (res.code == 1) {
                let mydate = new Date();
                mydate.setDate(mydate.getDate + 15);
                document.cookie = `token=${res.token};expires=${mydate}`;
                sessionStorage.setItem("token", res.token);
                this.$store.commit("initUser", JSON.stringify(res.data));
                this.$message({
                  message: "登录成功，跳转首页",
                  type: "success",
                });
                this.$router.push("/home");
              } else {
                this.$message({
                  message: res.msg,
                  type: "warning",
                });
              }
            });
        }
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style scoped>
.login {
  margin-top: 20px;
}
.loginForm {
  width: 500px;
  margin: 0 auto;
}
.avatar-uploader {
  display: block;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  display: block;
  margin: 0 auto;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-upload {
  display: block;
}
.el-upload img {
  width: 100px;
  height: 100px;
}
</style>